const SystemConfig = require('../models/SystemConfig')
const logger = require('../utils/logger')
const { HTTP_STATUS, ERROR_CODES } = require('../utils/constants')
const { asyncHandler, AppError } = require('../middleware/errorHandler')

class SystemConfigController {
  /**
   * 获取系统配置
   */
  static getConfig = asyncHandler(async (req, res) => {
    const { key } = req.params
    
    const config = await SystemConfig.get(key)
    
    if (config === null) {
      throw new AppError('配置项不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.CONFIG_NOT_FOUND)
    }
    
    res.json({
      success: true,
      data: {
        key,
        value: config
      }
    })
  })
  
  /**
   * 设置系统配置
   */
  static setConfig = asyncHandler(async (req, res) => {
    const { key } = req.params
    const { value, type = 'string', isEncrypted = false, isPublic = false, description = null, category = null } = req.body
    
    await SystemConfig.set(key, value, {
      type,
      isEncrypted,
      isPublic,
      description,
      category
    })
    
    logger.logSecurity('系统配置更新', {
      userId: req.user.id,
      key,
      isEncrypted
    })
    
    res.json({
      success: true,
      message: '配置设置成功',
      data: {
        key,
        value: isEncrypted ? '[加密]' : value
      }
    })
  })
  
  /**
   * 删除系统配置
   */
  static removeConfig = asyncHandler(async (req, res) => {
    const { key } = req.params
    
    const removed = await SystemConfig.remove(key)
    
    if (!removed) {
      throw new AppError('配置项不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.CONFIG_NOT_FOUND)
    }
    
    logger.logSecurity('系统配置删除', {
      userId: req.user.id,
      key
    })
    
    res.json({
      success: true,
      message: '配置删除成功'
    })
  })
  
  /**
   * 获取所有系统配置
   */
  static getAllConfigs = asyncHandler(async (req, res) => {
    const {
      category,
      publicOnly = 'false',
      includeEncrypted = 'false'
    } = req.query
    
    const options = {
      category,
      publicOnly: publicOnly === 'true',
      includeEncrypted: includeEncrypted === 'true'
    }
    
    const configs = await SystemConfig.getAll(options)
    
    res.json({
      success: true,
      data: {
        configs,
        count: Object.keys(configs).length
      }
    })
  })
  
  /**
   * 批量设置系统配置
   */
  static setBatchConfigs = asyncHandler(async (req, res) => {
    const { configs } = req.body
    
    if (!configs || typeof configs !== 'object') {
      throw new AppError('配置数据格式错误', HTTP_STATUS.BAD_REQUEST, ERROR_CODES.VALIDATION_ERROR)
    }
    
    const results = []
    const errors = []
    
    for (const [key, configData] of Object.entries(configs)) {
      try {
        const { value, type = 'string', isEncrypted = false, isPublic = false, description = null, category = null } = configData
        await SystemConfig.set(key, value, {
          type,
          isEncrypted,
          isPublic,
          description,
          category
        })
        results.push({ key, success: true })
      } catch (error) {
        errors.push({ key, success: false, error: error.message })
      }
    }
    
    logger.logSecurity('批量系统配置更新', {
      userId: req.user.id,
      successCount: results.length,
      errorCount: errors.length
    })
    
    res.json({
      success: errors.length === 0,
      message: `批量设置完成，成功: ${results.length}，失败: ${errors.length}`,
      data: {
        results,
        errors
      }
    })
  })
  
  /**
   * 重置配置到默认值
   */
  static resetToDefault = asyncHandler(async (req, res) => {
    const { key } = req.params
    
    const resetValue = await SystemConfig.resetToDefault(key)
    
    if (resetValue === null) {
      throw new AppError('配置项不存在或无默认值', HTTP_STATUS.NOT_FOUND, ERROR_CODES.CONFIG_NOT_FOUND)
    }
    
    logger.logSecurity('系统配置重置', {
      userId: req.user.id,
      key
    })
    
    res.json({
      success: true,
      message: '配置已重置为默认值',
      data: {
        key,
        value: resetValue
      }
    })
  })
  
  /**
   * 批量重置配置到默认值
   */
  static resetAllToDefault = asyncHandler(async (req, res) => {
    const results = await SystemConfig.resetAllToDefault()
    const successCount = results.filter(r => r.success).length
    
    logger.logSecurity('批量系统配置重置', {
      userId: req.user.id,
      resetCount: successCount
    })
    
    res.json({
      success: true,
      message: `已重置 ${successCount} 个配置项到默认值`,
      data: {
        results,
        resetCount: successCount
      }
    })
  })
  
  /**
   * 导出系统配置
   */
  static exportConfigs = asyncHandler(async (req, res) => {
    const {
      category,
      includeEncrypted = 'false',
      format = 'json'
    } = req.query
    
    const options = {
      categories: category ? [category] : null,
      includeEncrypted: includeEncrypted === 'true'
    }
    
    const exportData = await SystemConfig.exportConfigs(options)
    
    logger.logSecurity('系统配置导出', {
      userId: req.user.id,
      category,
      includeEncrypted: includeEncrypted === 'true',
      configCount: Object.keys(exportData.configs).length
    })
    
    if (format === 'json') {
      res.setHeader('Content-Type', 'application/json; charset=utf-8')
      res.setHeader('Content-Disposition', 'attachment; filename="system-config.json"')
      res.json(exportData)
    } else {
      // 转换为其他格式（如 YAML、INI 等）
      let content = ''
      for (const [key, config] of Object.entries(exportData.configs)) {
        content += `${key}=${JSON.stringify(config.value)}\n`
      }
      
      res.setHeader('Content-Type', 'text/plain; charset=utf-8')
      res.setHeader('Content-Disposition', 'attachment; filename="system-config.txt"')
      res.send(content)
    }
  })
  
  /**
   * 导入系统配置
   */
  static importConfigs = asyncHandler(async (req, res) => {
    const { configs, overwrite = false } = req.body
    
    if (!configs || typeof configs !== 'object') {
      throw new AppError('配置数据格式错误', HTTP_STATUS.BAD_REQUEST, ERROR_CODES.VALIDATION_ERROR)
    }
    
    const importResult = await SystemConfig.importConfigs({ configs }, { overwrite })
    
    logger.logSecurity('系统配置导入', {
      userId: req.user.id,
      overwrite,
      ...importResult
    })
    
    res.json({
      success: true,
      message: '配置导入完成',
      data: importResult
    })
  })
  
  /**
   * 验证配置值
   */
  static validateConfig = asyncHandler(async (req, res) => {
    const { key } = req.params
    const { value, type = 'string' } = req.body
    
    try {
      SystemConfig.validateValue(key, value, type)
      
      res.json({
        success: true,
        message: '配置值验证通过',
        data: {
          key,
          originalValue: value,
          type
        }
      })
    } catch (error) {
      res.status(HTTP_STATUS.BAD_REQUEST).json({
        success: false,
        message: '配置值验证失败',
        error: error.message
      })
    }
  })
  
  /**
   * 获取配置历史记录
   */
  static getConfigHistory = asyncHandler(async (req, res) => {
    const { key } = req.params
    const { limit = 20 } = req.query
    
    const history = await SystemConfig.getConfigHistory(key, parseInt(limit))
    
    res.json({
      success: true,
      data: {
        history,
        count: history.length
      }
    })
  })
  
  /**
   * 清除配置缓存
   */
  static clearCache = asyncHandler(async (req, res) => {
    const { key } = req.params
    
    if (key) {
      // 清除特定配置的缓存
      SystemConfig.clearCache(key)
    } else {
      // 清除所有配置缓存
      SystemConfig.clearAllCache()
    }
    
    logger.logSecurity('系统配置缓存清除', {
      userId: req.user.id,
      key: key || 'all'
    })
    
    res.json({
      success: true,
      message: key ? `配置 ${key} 的缓存已清除` : '所有配置缓存已清除'
    })
  })
  
  /**
   * 获取配置统计信息
   */
  static getConfigStats = asyncHandler(async (req, res) => {
    const stats = await SystemConfig.getStats()
    
    res.json({
      success: true,
      data: {
        stats
      }
    })
  })
}

module.exports = SystemConfigController